package com.fang.transfer.file.client.thread;

import com.fang.transfer.file.client.AppContext;
import com.fang.transfer.file.client.connection.UdpUtil;
import com.fang.transfer.file.client.transfer.UdpService;
import com.fang.transfer.file.client.util.IndexUtil;
import com.fang.transfer.file.common.code.ClientSendCode;
import com.fang.transfer.file.common.model.TransferFileRequest;
import com.fang.transfer.file.common.model.User;

import java.io.RandomAccessFile;
import java.net.DatagramPacket;
import java.net.InetSocketAddress;
import java.util.ArrayList;

/**
 * 发送文件,根据下标(发送方)
 */
public class SendFileByIndex implements Runnable {

    private TransferFileRequest request;
    private ArrayList<Integer> indexList;
    private User receiveUser;
    private RandomAccessFile rf;

    public SendFileByIndex(TransferFileRequest param) throws Exception {
        this.indexList = param.getReSendIndex();
        this.request = AppContext.transferFileRequestMap.get(param.getId());
        this.request.setStatus(4);
        this.receiveUser = request.getReceiveUser();
        this.rf = AppContext.randomAccessFileMap.get(param.getId());
        if (this.rf == null) {
            this.rf = new RandomAccessFile(request.getPath(), "rw");
            AppContext.randomAccessFileMap.put(param.getId(), this.rf);
        }
    }

    @Override
    public void run() {

        try {
            Thread.currentThread().setName("SendFileByIndex");
            doRun();
        } catch (InterruptedException exception) {
            System.out.println("结束文件发送");
        } catch (Exception ex) {
            ex.printStackTrace();
        }


    }

    private void doRun() throws Exception {

        UdpService udpService = AppContext.udpServiceMap.get(request.getId());
        int dataMaxLength = UdpUtil.PACKAGE_LENGTH - 2;
        byte[] bytes = new byte[UdpUtil.PACKAGE_LENGTH];
        InetSocketAddress address = new InetSocketAddress(receiveUser.getHost(), receiveUser.getPort());
        for (Integer index : indexList) {
            System.out.println("发送下标:" + index);
            rf.seek(dataMaxLength * index);
            IndexUtil.updateByteArr(bytes, index);
            int read = rf.read(bytes, 2, dataMaxLength);
            DatagramPacket packet = new DatagramPacket(bytes, read + 2, address);
            udpService.sendData(packet);
        }
        System.out.println("传输结束,进入验证阶段");
        AppContext.tcpUtil.writeAndFlush(ClientSendCode.SEND_FILE_FINISH_TO_RECEIVE, request);
    }
}
